﻿using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ZechatApp.Services;

public static class CommonService
{
    public static (int, int) GetFreePorts()
    {
        int send;
        int listen;

        using (var tcpListener = new TcpListener(IPAddress.Loopback, 0))
        {
            tcpListener.Start();
            send = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
            tcpListener.Stop();
        }

        using (var tcpListener = new TcpListener(IPAddress.Loopback, 0))
        {
            tcpListener.Start();
            listen = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
            tcpListener.Stop();
        }

        return (send, listen);
    }

    public static string RunInjectExe(string exePath, string arguments)
    {
        var startInfo = new ProcessStartInfo
        {
            FileName = exePath,
            Arguments = arguments,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using var process = new Process();
        process.StartInfo = startInfo;
        process.Start();

        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        using var streamReader = new StreamReader(process.StandardOutput.BaseStream, Encoding.GetEncoding("gb18030"));
        var output = streamReader.ReadToEnd();
        using var errorReader = new StreamReader(process.StandardError.BaseStream, Encoding.GetEncoding("gb18030"));
        var error = errorReader.ReadToEnd();
        process.WaitForExit();

        return !string.IsNullOrEmpty(error) ? $"Error: {error}" : output;
    }

    public static string DecodeCNEncodeToUtf8(string cnString)
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        var cnBytes = Encoding.GetEncoding("gb18030").GetBytes(cnString);
        var utf8String = Encoding.UTF8.GetString(cnBytes);
        return utf8String;
    }
}